package com.idp.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.idp.common.enums.MessageEnum;
import com.idp.common.error.SystemException;
import com.idp.common.model.PageModel;
import com.idp.system.dto.SysFileDto;
import com.idp.system.dto.SysFileSearchDto;
import com.idp.system.entity.SysFileEntity;
import com.idp.system.mapper.SysFileMapper;
import com.idp.system.service.SysFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 文件表Service实现类
 * @author King
 */
@Service("sysFileService")
public class SysFileServiceImpl implements SysFileService {

	@Autowired
	private SysFileMapper sysFileMapper;

	@Override
	public PageModel<SysFileDto> findByPage(SysFileSearchDto sysFileSearchDto) {

		PageModel<SysFileDto> page = new PageModel<SysFileDto>();

		if(sysFileSearchDto.getEndDate() != null) {
			sysFileSearchDto.setEndDate(DateUtil.endOfDay(sysFileSearchDto.getEndDate()));
		}

		page.setList(sysFileMapper.getList(sysFileSearchDto));

		return page;
	}

	@Override
	public SysFileDto getById(String id) {

		if(ObjectUtil.isEmpty(id)) {
			throw new SystemException(MessageEnum.PARAM_ERROR);
		}

		SysFileDto sysFileDto = sysFileMapper.getById(id);

		if(sysFileDto == null) {
			throw new SystemException(MessageEnum.DATA_NOT_EXIST);
		}

		return sysFileDto;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void add(SysFileDto sysFileDto) {

		SysFileEntity sysFileEntity = BeanUtil.toBean(sysFileDto, SysFileEntity.class);

		sysFileMapper.insert(sysFileEntity);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void update(SysFileDto sysFileDto) {

		SysFileEntity sysFileEntity = sysFileMapper.selectById(sysFileDto.getId());

        if(sysFileEntity == null) {
            throw new SystemException(MessageEnum.DATA_NOT_EXIST);
        }

		BeanUtil.copyProperties(sysFileDto, sysFileEntity);

		sysFileMapper.updateById(sysFileEntity);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delete(String id) {

		SysFileEntity sysFileEntity = sysFileMapper.selectById(id);

        if(sysFileEntity == null) {
            throw new SystemException(MessageEnum.DATA_NOT_EXIST);
        }

		sysFileMapper.deleteById(id);
	}

}
